// Package middleware contains reusable HTTP middlewares, including API key auth and RBAC.
package middleware

import (
	"net/http"
	"strings"
)

// Simple API key auth + role via header
// Header: X-API-Key, X-Role (admin/user)

type AuthConfig struct {
	Keys map[string]string // key -> role ("admin"/"user")
}

func APIKeyAuth(conf AuthConfig) func(http.Handler) http.Handler {
	return func(next http.Handler) http.Handler {
		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			key := r.Header.Get("X-API-Key")
			if key == "" {
				http.Error(w, "unauthorized", http.StatusUnauthorized)
				return
			}
			role, ok := conf.Keys[key]
			if !ok {
				http.Error(w, "forbidden", http.StatusForbidden)
				return
			}
			// attach role to context
			ctx := r.Context()
			ctx = WithRole(ctx, role)
			next.ServeHTTP(w, r.WithContext(ctx))
		})
	}
}

// RBAC: allow roles for certain methods/prefixes
func RequireRole(roles ...string) func(http.Handler) http.Handler {
	allowed := map[string]struct{}{}
	for _, r := range roles {
		allowed[strings.ToLower(r)] = struct{}{}
	}
	return func(next http.Handler) http.Handler {
		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			role := RoleFromContext(r.Context())
			if _, ok := allowed[strings.ToLower(role)]; !ok {
				http.Error(w, "forbidden", http.StatusForbidden)
				return
			}
			next.ServeHTTP(w, r)
		})
	}
}
